<?php
/**
 * 面包屑
 * Created by PhpStorm.
 * User: yui
 * Date: 2016/11/17 0017
 * Time: 1:18
 */

namespace common\services;

use Yii;
use mdm\admin\models\Menu;
use yii\helpers\Url;

class MenuSve extends BaseSve
{

    /**
     * 获取用户菜单
     */
    public static function getUserMenus()
    {
        if (Yii::$app->user->isGuest) {
            Yii::$app->user->logout();
            header('Location: ' . HTTP_DOMAIN_ADMIN . Url::toRoute(Yii::$app->user->loginUrl));
            exit;
        }
        //用户ID
        $userId = Yii::$app->user->id;
        $db = Yii::$app->db;
        //根据ID查找权限
        $routing = $db->createCommand("SELECT aic2.child FROM auth_assignment AS aa 
                                        LEFT JOIN auth_item_child AS aic ON aa.item_name = aic.parent 
                                        LEFT JOIN auth_item_child AS aic2 ON aic.child = aic2.parent
                                        WHERE aa.user_id = {$userId}")->queryColumn();
        //查找菜单
        $parentMenus = Menu::find()->where(['parent' => null])->orderBy('order ASC, id ASC')->asArray()->all();
        $childMenus = Menu::find()->where(['route' => $routing])->orderBy('order ASC, id ASC')->asArray()->all();
        //当前路由
        $requestedRoute = empty(Yii::$app->requestedRoute) ? '/home/index' : '/' . Yii::$app->requestedRoute;
        //处理菜单，并判断当前菜单位置
        foreach ($parentMenus as &$pv) {
            $pv['child'] = [];
            $pv['data'] = !empty($pv['data']) ? json_decode($pv['data'], true) : [];
            $pv['this'] = false;
            foreach ($childMenus as $cv) {
                $cv['this'] = false;
                //如果等于当前子菜单
                if ($requestedRoute == $cv['route']) {
                    $cv['this'] = true;
                }
                $cv['data'] = !empty($cv['data']) ? json_decode($cv['data'], true) : [];
                if ($pv['id'] == $cv['parent']) {
                    if ($cv['this']) {
                        $pv['this'] = true;
                    }
                    array_push($pv['child'], $cv);
                }
            }
        }
        //如果没有子菜单，删除父菜单
        for ($i = 0; $i < count($parentMenus); $i++) {
            if (empty($parentMenus[$i]['child'])) {
                unset($parentMenus[$i]);
            }
        }
        return $parentMenus;
    }

    /**
     * 标题和面包屑
     * @param $obj
     */
    public static function getBreadcrumbs(&$obj)
    {
        //当前路由
        $route = '/' . $obj->context->module->requestedRoute;
        if ($route === '/') {
            //如果是默认路由
            $menuList = ['系统概况', '系统详情'];
        } else {
            //查询菜单
            $menuList = Yii::$app->db->createCommand("SELECT aic.parent,m.`name` FROM `menu` AS m, auth_item_child AS aic WHERE aic.child = m.route AND m.route='{$route}'")->queryOne();
        }
        //添加面包屑
        $obj->params['breadcrumbs'] = $menuList;
        //添加标题
        $obj->title = end($menuList);
    }
}